﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Odyssey.Controls
{
    public class TilePanel : Panel
    {


        public double TileWidth
        {
            get { return (double)GetValue(TileWidthProperty); }
            set { SetValue(TileWidthProperty, value); }
        }

        public static readonly DependencyProperty TileWidthProperty =
            DependencyProperty.Register("TileWidth", typeof(double), typeof(TilePanel), new PropertyMetadata(96.0));



        public double TileHeight
        {
            get { return (double)GetValue(TileHeightProperty); }
            set { SetValue(TileHeightProperty, value); }
        }

        public static readonly DependencyProperty TileHeightProperty =
            DependencyProperty.Register("TileHeight", typeof(double), typeof(TilePanel), new PropertyMetadata(96.0));


        private int columns = 1;

        protected override Size MeasureOverride(Size availableSize)
        {
            double tileWidth = Math.Max(1.0, TileWidth);
            double tileHeight = TileHeight;
            double aWidth = availableSize.Width;
            double aHeight = availableSize.Height;

            if (double.IsInfinity(aWidth)) aWidth = tileWidth;

            columns = Math.Max(1, (int)Math.Ceiling(aWidth / tileWidth));
            int count = Children.Count;

            int rows = ((count + columns - 1) / columns);
            aHeight = rows * tileHeight;

            Size tileSize = new Size(tileWidth, tileHeight);

            foreach (UIElement child in Children)
            {
                child.Measure(tileSize);
            }

            return new Size(aWidth, aHeight);

        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            double tw = TileWidth;
            double th = TileHeight;
            Rect rect = new Rect(0.0, 0.0, tw, th);

            int columns = Math.Max(1, this.columns);
            int col = 0;
            foreach (UIElement child in Children)
            {
                child.Arrange(rect);
                if (++col >= columns)
                {
                    col = 0;
                    rect.Y += th;
                    rect.X = 0.0;
                }
                else
                {
                    rect.X += tw;
                }
            }
            return finalSize;
        }

    }
}
